package com.xyy.saas.payment.callback.core.job;

import com.xyy.saas.payment.adpater.impl.FuminAdapter;
import com.xyy.saas.payment.callback.core.result.CallbackRunner;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.cores.bo.QueryResultBo;
import com.xyy.saas.payment.cores.vo.CallbackResultVo;
import com.xyy.saas.payment.dao.model.PayResultOrder;
import com.xyy.saas.payment.dao.model.RefundOrder;
import com.xyy.saas.payment.merchant.core.dto.QueryTransactionStatusDto;
import com.xyy.saas.payment.payment.core.service.RefundOrderService;
import com.xyy.saas.payment.service.PayResultOrderService;
import com.xyy.saas.payment.util.ApolloUtil;
import com.xyy.saas.payment.util.DateUtil;
import com.xyy.saas.payment.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 同步退款状态
 */
@Slf4j
@Service
public class SyncFMRefundStatusJob {
    @Resource
    private RefundOrderService refundOrderService;
    @Resource
    private PayResultOrderService payResultOrderService;
    @Resource
    private FuminAdapter fuminAdapter;
    @Resource
    private CallbackRunner callbackRunner;

    public void execute(String refundNo, Byte status) {
        // 退款中
        syncStatus(status, refundNo);
    }

    private void syncStatus(Byte status, String refundNo) {
        long startTime = System.currentTimeMillis();
        log.info("SyncFMRefundStatusJob#execute start.");

        int pageOffset = 0;
        int pageSize = 50;

        while(true) {
            List<RefundOrder> items = refundOrderService.
                    selectListByStatusAndPayChannel(Constants.CHANNEL_FUMIN_BANK_NAME, status, pageOffset, pageSize);

            if(CollectionUtils.isEmpty(items)) {
                break;
            }

            for(RefundOrder item : items) {
                if(StringUtils.isNotBlank(refundNo) && !Objects.equals(refundNo, item.getRefundNo())) {
                    continue;
                }

                try {
                    PayResultOrder resultOrder = payResultOrderService.selectByPayNoAndChannel(item.getPayNo(), item.getChannel());

                    String transactionNo = item.getRefundNo();

                    if(org.apache.commons.lang.StringUtils.isNotBlank(item.getChannelRefundNo()) && item.getChannelRefundNo().startsWith(Constants.TOTAL_ORDER_NUMBER_PREFIX)) {
                        transactionNo = item.getChannelRefundNo().substring(NumberUtils.INTEGER_ONE);
                    }

                    QueryTransactionStatusDto queryTransactionStatusDto = QueryTransactionStatusDto.
                            build(resultOrder.getBusinessOrderType(), transactionNo, QueryTransactionStatusDto.TRADE_TYPE_REFUND, getPayeeAccountId(item.getUserId()), item.getUpdateTime());
                    QueryResultBo queryResultBo = fuminAdapter.queryTransactionStatus(queryTransactionStatusDto);

                    if(queryResultBo == null) {
                        if(RefundOrder.STATUS_CREATE.equals(item.getStatus())) {
                            // 1.更新
                            item.setStatus(RefundOrder.STATUS_FAIL);
                            refundOrderService.update(item);
                        }

                        continue;
                    }

                    switch(queryResultBo.getStatus()) {
                        case QueryResultBo.PROCESSING:
                            break;
                        case QueryResultBo.FINISHED:
                            Long unixTime = queryResultBo.getSuccessTime() / 1000;

                            // 1.更新
                            item.setStatus(RefundOrder.STATUS_FINISH);
                            item.setSuccessTime(DateUtil.unixToDate(unixTime));
                            refundOrderService.update(item);

                            // 2.通知业务
                            callbackRunner.callback(item.getRefundNo(), CallbackResultVo.TYPE_REFUND_SUCCESS, item.getAmount(),
                                    unixTime, item.getCallbackAddress(), resultOrder.getMerchantId(), item.getBusinessRefundNo());
                            break;
                        case QueryResultBo.FAILED:
                            // 1.更新
                            item.setStatus(RefundOrder.STATUS_FAIL);
                            refundOrderService.update(item);

                            // 2.通知业务
                            callbackRunner.callback(item.getRefundNo(), CallbackResultVo.TYPE_REFUND_FAIL, item.getAmount(),
                                    0L, item.getCallbackAddress(), resultOrder.getMerchantId(), item.getBusinessRefundNo());
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported Operation refund status. queryResultBo=" + JSONUtils.toJSON(queryResultBo));
                    }
                }
                catch(Exception ex) {
                    log.error(ex.getMessage() + ", refundOrder=" + JSONUtils.toJSON(item), ex);
                }
            }

            if(items.size() < pageSize) {
                break;
            }

            pageOffset += pageSize;
        }

        log.info("SyncFMRefundStatusJob#execute end. cost={}", (System.currentTimeMillis() - startTime));
    }

    /**
     * 获取收款人信息
     */
    private String getPayeeAccountId(String accountId) {
        if(StringUtils.isBlank(accountId)) {
            return accountId;
        }

        return Objects.equals(ApolloUtil.getProperty(Constants.POP_DIRECT_PAY_YBM_TECH_USER_ID), accountId) ?
                ApolloUtil.getProperty(Constants.EC_POP_BIG_SHOP_PINGAN_ACCOUNT_ID) : accountId;
    }
}
